#coding:utf-8
'''
Created on 2015��9��9��

@author: guowu
'''
from PyQt4.QtGui import QWidget, QApplication, QTableWidget, QFrame,\
    QAbstractItemView, QHeaderView, QLabel, QVBoxLayout, QHBoxLayout, QFont,\
    QTableWidgetItem, QPushButton, QCursor, QMenu, QAction, QItemSelectionModel,\
    QPainterPath, QColor, QPainter, QPen, QBrush, QIcon
import sys
from PyQt4.QtCore import QSize, Qt, QStringList, QTextCodec, QPoint, SIGNAL,\
    QRect
import math
QTextCodec.setCodecForTr(QTextCodec.codecForName("utf-8"))

class ListWidget(QWidget):
    def __init__(self,parent=None):
        super(ListWidget,self).__init__(parent)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setFixedSize(QSize(420,450))
        
        self.titleLabel = QLabel(self)
        self.titleLabel.setFixedSize(QSize(400,30))
        self.titleLabel.setText(self.tr("列    表    显    示        "))
        self.titleLabel.setAlignment(Qt.AlignCenter)
        self.titleLabel.setStyleSheet("background-color:gray;color:white;") #设置选中背景色
        self.titleLabel.setFont(QFont(self.tr("微软雅黑"),11))
        
        self.closeButton = QPushButton(self)
        self.closeButton.setFixedSize(QSize(20,20))
        self.closeButton.setIcon(QIcon("close.png"))
        self.closeButton.setIconSize(QSize(20,20))
        self.closeButton.setStyleSheet("QPushButton{background-color:rgb(200,100,100,0);border:0px;}"
                                    "QPushButton:hover{background-color:rgb(255,100,200);}"
                                    "QPushButton:pressed{background-color:rgb(100,100,100);}")
        self.connect(self.closeButton, SIGNAL("clicked()"),self.close)
        
        
        self.contentMap = {0:{"name":"boom clam","time":"1:10:10"},1:{"name":"sun","time":"1:10:11"},2:{"name":"moon","time":"1:10:20"}}
        
        self.listTableWidget = QTableWidget(self)
        #QPalette pll = self.listTableWidget.palette()
        #pll.setBrush(QPalette.Base,QBrush(QColor(255,255,255,0)))
        #self.listTableWidget.setPalette(pll)
        #self.listTableWidget.horizontalHeader().setStyleSheet("QHeaderView.section {background-color:lightbluecolor: blackpadding-left: 4pxborder: 1px solid #6c6c6c}")
        
        #设置表头内容
        header = QStringList()
        header.append(self.tr("名称"))
        header.append(self.tr("时间"))
        header.append(self.tr("操作"))
        
        #设置表头字体加粗
        #QFont font = self.listTableWidget.horizontalHeader().font()
        #font.setBold(True)
        #self.listTableWidget.horizontalHeader().setFont(font)
        
        
        self.listTableWidget.setFrameShape(QFrame.NoFrame) #设置无边框
        self.listTableWidget.setShowGrid(False) #设置不显示格子线
        self.listTableWidget.setFocusPolicy(Qt.NoFocus) #去除选中虚线框
        
        self.listTableWidget.setSelectionMode(QAbstractItemView.ExtendedSelection) #可多选（Ctrl、Shift、 Ctrl+A都可以）
        self.listTableWidget.setSelectionBehavior(QAbstractItemView.SelectRows) #设置选择行为时每次选择一行
        
        self.listTableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers) #设置不可编辑
        
        
        self.listTableWidget.verticalHeader().setVisible(False) #设置垂直头不可见
        self.listTableWidget.horizontalHeader().setFixedHeight(25) #设置表头的高度
        #self.listTableWidget.horizontalHeader().setDefaultSectionSize(50)#设置列距
        self.listTableWidget.horizontalHeader().setClickable(False) #设置表头不可点击（默认点击后进行排序）
        self.listTableWidget.horizontalHeader().setStretchLastSection(True) #设置充满表宽度
        
        #self.listTableWidget.verticalHeader().setResizeMode(QHeaderView.ResizeToContents)#设置行距自适应
        self.listTableWidget.verticalHeader().setDefaultSectionSize(25) #设置行距
        
        #单双行颜色交替
        self.listTableWidget.setAlternatingRowColors(True)
        #设置tablewidget网格
        self.listTableWidget.setShowGrid(False)
        
        
        
        #点击事件
        self.connect(self.listTableWidget,SIGNAL("itemDoubleClicked(QTableWidgetItem*)"),self.slotRead)
        #self.connect(self.listTableWidget,SIGNAL("itemClicked(QTableWidgetItem*)"),self.slotRead)
        
        #设置右键菜单
        self.listTableWidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.listTableWidget.customContextMenuRequested.connect(self.on_tableWidgetHost_customContextMenuRequested)
        self.centerTableMenu = QMenu(self.listTableWidget)
        self.delCenterAction = QAction(u"删 除", self)
        self.editCenterAction = QAction(u"编 辑", self)
        #self.connect(self.delCenterAction, SIGNAL("triggered()"), self.on_pushButtonDelete_clicked)
        #self.connect(self.editCenterAction, SIGNAL("triggered()"), self.slotEdit)
        
        
        self.listTableWidget.setStyleSheet("background: rgb(155,255,250); alternate-background-color:rgb(205,255,250);selection-color:rgb(255,255,255);selection-background-color:qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgb(146,46,146),stop:1 rgb(66,66,66));") #设置选中背景色
        self.listTableWidget.horizontalHeader().setStyleSheet("QHeaderView:section{background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgb(146,46,146),stop:1 rgb(66,66,66));color: rgb(210,210,210);padding-left: 4px;border: 1px solid #383838;}") #设置表头背景色
        
        #设置水平、垂直滚动条样式
#         self.listTableWidget.horizontalScrollBar().setStyleSheet("QScrollBar{background:red; height:10px;}"
#                                                                  "QScrollBar:handle{background:lightgray; border:2px solid transparent; border-radius:5px;}"
#                                                                  "QScrollBar:handle:hover{background:gray;}"
#                                                                  "QScrollBar:sub-line{background:transparent;}"
#                                                                  "QScrollBar:add-line{background:transparent;}")
        self.listTableWidget.verticalScrollBar().setStyleSheet("QScrollBar{background:white; width: 10px;border-radius:5px;}"
                                                               
                                                               "QScrollBar:sub-line{background:lightgray;border-radius:5px;}"
                                                               "QScrollBar:sub-line:hover{background:gray;border-radius:5px;}"
                                                               "QScrollBar:add-line{background:lightgray;border-radius:5px;}"
                                                               "QScrollBar:add-line:hover{background:gray;border-radius:5px;}"
                                                               
                                                               "QScrollBar:handle{background:lightgray ;border:2px solid transparent ;border-radius:5px;}"
                                                               "QScrollBar:handle:hover{background:gray;}"
                                                               
                                                               "QScrollBar:add-page{background:transparent;border-radius:5px;}"#滚动条下端
                                                               "QScrollBar:sub-page{background:transparent;border-radius:5px;}"#滚动条下端
                                                               )
#                                                                QScrollBar::add-page:vertical,QScrollBar::sub-page:vertical   // 当滚动条滚动的时候，上面的部分和下面的部分
#                                                                 {
#                                                                     background:rgba(0,0,0,10%);
#                                                                     border-radius:4px;
#                                                                 })
        #/*QPalette pal
        #pal.setColor(QPalette.Base, QColor(255, 0, 0))
        #pal.setColor(QPalette.AlternateBase, QColor(0, 255, 0))
        #self.listTableWidget.setPalette(pal)*/
        self.listTableWidget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        #self.listTableWidget.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        
        
        self.listTableWidget.setColumnCount(3)
        self.listTableWidget.setHorizontalHeaderLabels(header)
        self.listTableWidget.setColumnWidth(0,200)
        self.listTableWidget.setColumnWidth(1,100)
        self.listTableWidget.horizontalHeader().setResizeMode(QHeaderView.Fixed)
        self.listTableWidget.setRowCount(23)
        self.listTableWidget.setFixedWidth(400)
        self.listTableWidget.setFixedHeight(400)
        #self.listTableWidget.verticalHeader().setDefaultSectionSize(tableWidth+10)
        #self.listTableWidget.horizontalHeader().setDefaultSectionSize((parentWidth-100)/columnCount)
        
        self.titleLabel.move(QPoint((self.width()-self.titleLabel.width())/2,10))
        
        self.listTableWidget.move(QPoint((self.width()-self.listTableWidget.width())/2,40))
        
        self.closeButton.move(QPoint(self.width()-30,10))
        
        self.refreshListWidget()
        
        #设置让某个单元格或某行选中*/  注意代码的位置，要在设置完航和列数之后
        #self.listTableWidget.setCurrentCell(0, 0, QItemSelectionModel.Select) #设置某个单元格被选中
        #self.listTableWidget.setCurrentCell(0, QItemSelectionModel.Select)  #设置某一行被选中
        
        self.mousePressed = False
        
    def slotRead(self,item):
        print item.text()
        print item.row()
        selectitem = self.listTableWidget.item(item.row(), 0)
        print selectitem.data(Qt.UserRole).toString()
        print selectitem.data(Qt.UserRole+1).toString()
        print selectitem.data(Qt.UserRole+2).toString()
        
        
        
    def refreshListWidget(self):
        for item in self.contentMap:
            
            #name
            pTWItemId = QTableWidgetItem(self.contentMap[item]["name"])
            pTWItemId.setTextAlignment(Qt.AlignLeft|Qt.AlignBottom)
            pTWItemId.setToolTip(self.contentMap[item]["name"])
            pTWItemId.setData(Qt.UserRole, "nameone")
            pTWItemId.setData(Qt.UserRole + 1, "nametwo")
            pTWItemId.setData(Qt.UserRole + 2, "namethree")
            self.listTableWidget.setItem(item, 0, pTWItemId)
            #time
            pTWItemId = QTableWidgetItem(self.contentMap[item]["time"])
            pTWItemId.setTextAlignment(Qt.AlignLeft|Qt.AlignBottom)
            pTWItemId.setToolTip(self.contentMap[item]["time"])
            pTWItemId.setData(Qt.UserRole, self.contentMap[item]["time"])
            pTWItemId.setData(Qt.UserRole + 1, self.contentMap[item]["time"])
            pTWItemId.setData(Qt.UserRole + 2, self.contentMap[item]["time"])
            self.listTableWidget.setItem(item, 1, pTWItemId)
            
            
            pLableSex = QPushButton(self.tr("操作"))
            pLableSex.setFixedSize(QSize(30,20))
            pLableSex.setObjectName(self.contentMap[item]["name"])
            pLableSex.setStyleSheet("QPushButton{background-color:rgb(200,100,100);color:white;border:0px;}"
                                    "QPushButton:hover{background-color:rgb(10,100,10);}"
                                    "QPushButton:pressed{background-color:rgb(0,0,0,0);}")
            self.connect(pLableSex, SIGNAL("clicked()"),self.slotOperate)
            qwidget = QWidget()
            qwidget.setStyleSheet("background-color:rgb(0,0,0,0);")
            hlayout = QHBoxLayout()
            hlayout.setMargin(0)
            hlayout.setSpacing(0)
            hlayout.addStretch()
            hlayout.addWidget(pLableSex)
            hlayout.addStretch()
            vlayout = QVBoxLayout()
            vlayout.setMargin(0)
            vlayout.setSpacing(0)
            vlayout.addStretch()
            vlayout.addLayout(hlayout)
            qwidget.setLayout(vlayout)
            
            self.listTableWidget.setCellWidget (item, 2, qwidget)
            
        
    def slotOperate(self):
        btn = self.sender()
        print btn.objectName()
        
        
    def on_tableWidgetHost_customContextMenuRequested(self,pos):
        item = self.listTableWidget.itemAt(pos)
        if (item != None):
            self.centerTableMenu.clear()
            self.centerTableMenu.addAction(self.delCenterAction)
            self.centerTableMenu.addAction(self.editCenterAction)
            self.centerTableMenu.exec_(QCursor.pos())   
            
            
        
    def paintEvent(self,event):
        m = 8
        
        path = QPainterPath()
        path.setFillRule(Qt.WindingFill)
        path.addRect(m, m, self.width()-m*2, self.height()-m*2)
        painter = QPainter(self)
        #painter.setRenderHint(QPainter.Antialiasing, True)
        painter.fillPath(path, QBrush(Qt.gray))
     
        color = QColor(100, 100, 100, 30)
        #for(int i=0; i<10; i++)
        
        for i in range(m):
            path = QPainterPath()
            path.setFillRule(Qt.WindingFill)
            path.addRoundRect(m-i, m-i, self.width()-(m-i)*2, self.height()-(m-i)*2,1,1)
            color.setAlpha(90 - math.sqrt(i)*30)
            painter.setPen(QPen(color,1,Qt.SolidLine))
            painter.drawRoundRect(QRect(m-i, m-i, self.width()-(m-i)*2, self.height()-(m-i)*2), 0,0)
          
            '''path = QPainterPath()
            path.setFillRule(Qt.WindingFill)
            path.addRect(m-i, m-i, self.width()-(m-i)*2, self.height()-(m-i)*2)
            color.setAlpha(90 - math.sqrt(i)*30)
            painter.setPen(QPen(color,1))
            painter.drawPath(path)'''
            
        
    def mouseMoveEvent(self,event):
        self.move(QPoint(self.pos() + event.pos() - self.currentPos))
        
    
    def mousePressEvent(self,event):
        self.currentPos = event.pos()
        
        

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ListWidget()
    window.show()
    app.exec_()